<template>
  <div class="container">
    <div class="header">
      <div class="title">水位监测</div>
      <div class="time">
        <img src="../../static/images/icon-time.png" alt="">
        <span>{{ currentYearMonth1 }}-{{ currentYearMonth2 }}</span>
      </div>
    </div>
    <div class="unit">单位:座</div>
    <div class="content">
      <div class="title">
        <div>水位监测详情</div>
        <img src="../../static/images/Subtract.png" alt="" @click="handleShow" />
      </div>
      <div class="amount">        
        <div class="info">
          <img src="../../static/images/water-level-bg-icon.png" alt="">
          <div class="detail">
            <div class="name">水位监测站数量（个）</div>
            <div class="value">{{ waterlevelStationSum }}</div>
          </div>
        </div> 
      </div>
      <div class="search">
        <van-search
          v-model="searchValue"
          @search="onSearch"
          show-action
          placeholder="请输入要查询的水位监测站名称"
        >
          <template #action>
            <div @click="clickSearch">搜索</div>
          </template>
        </van-search>
        <div class="search-list" v-show="isShowSearchList">
          <div 
            v-for="(item,index) in searchList" 
            :key="index" 
            class="search-item"
            @click="handleChoose(item.stationName)"
          >
            {{ item.stationName }}
          </div>
        </div>
      </div>
      <div class="choose">
        <div class="left">
          <div class="option">
            <div @click="getLeftList">
              <input
                class="choose-input"
                type="text"
                placeholder="所属区域中心"
                readonly="readonly"
                v-model="leftVal"                
              />
              <van-icon :name="showLeft?'arrow-up':'arrow-down'" size="14" style="position: absolute;right: 5%;top: 20%;" />
            </div>
            <div class="choose-list" v-show="showLeft">
              <div class="list">
                <li                  
                  v-for="item in leftList"
                  @click="setLeft(item)"
                  :key="item.region"
                >
                  {{ item.region }}
                </li>
              </div>              
            </div>
          </div>
        </div>
        <div class="right">
          <div class="option">
            <div @click="getRightList">
              <input
                class="choose-input"
                type="text"
                placeholder="所属航道"
                readonly="readonly"
                v-model="rightVal"   
              />
              <van-icon :name="showRight?'arrow-up':'arrow-down'" size="14" style="position: absolute;right: 5%;top: 20%;" />
            </div>            
            <div class="choose-list" v-show="showRight">
              <div class="list">
                <li                 
                  v-for="item in rightList"
                  @click="setRight(item)"
                  :key="item.waterwayName"
                >
                  {{ item.waterwayName }}
                </li>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="table-box">
        <div class="table" style="margin-top: 20px; width: 690px">
          <table
            style="border-collapse: collapse"
            cellspacing="0"
            cellpadding="0"
          >
            <thead style="background: #f8f9fb;position: sticky;top: -1px;">
              <tr style="border: 1px solid #d9d9d9;">  
                <th style="width: 30px;"></th>
                <th style="width: 80px">区域中心</th>
                <th style="width: 100px">监测站名称</th>
                <th style="width: 100px">水位值(m)</th>
                <th style="width: 180px">所属航道</th>                                
                <th style="width: 200px">数据更新时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in tableData1" :key="index">
                <td style="width: 30px;">
                  <input type="radio" :checked="isChecked===index?true:false" @click="handleChecked(item,index)">
                </td>
                <td style="width: 80px">
                  <strong>{{ item.region }}</strong>
                </td>
                <!-- <van-popover :actions="[{text: item.waterlevelStation}]" position="top-start" actions-direction="horizontal" theme="dark">
                  <template #reference> -->
                    <td style="max-width: 100px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                        {{ item.waterlevelStation }}
                    </td>
                  <!-- </template>
                </van-popover> -->
                <td style="width: 100px">{{ item.waterLevel }}</td>
                <td style="width: 180px">{{ item.waterway }}</td>                               
                <td style="width: 200px">{{ item.updateTime }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="title">
        <div>水位监测趋势</div>
        <img src="../../static/images/Subtract.png" alt="" @click="handleShow" />
      </div>
      <div class="sub-name">监测站名称：{{ searchValue }}</div>
      <!-- <div class="search">
        <van-search
          v-model="searchValue2"
          @search="onSearch2"
          placeholder="请输入要查询的水位监测站名称"
        >
        </van-search>
        <div class="search-list" v-show="isShowSearchList2">
          <div 
            v-for="(item,index) in searchList2" 
            :key="index" 
            class="search-item"
            @click="handleChoose2(item.stationName)"
          >
            {{ item.stationName }}
          </div>
        </div>
      </div> -->
      <div class="tab-list">
        <div class="tab-item" :class="timeInterval === 0 ? 'active' : ''"  @click="getTimeInterval(0)">自定义时段</div>
        <div class="tab-item" :class="timeInterval === 1 ? 'active' : ''"  @click="getTimeInterval(1)">近1天</div>
        <div class="tab-item" :class="timeInterval === 3 ? 'active' : ''"  @click="getTimeInterval(3)">近3天</div>
        <div class="tab-item" :class="timeInterval === 7 ? 'active' : ''"  @click="getTimeInterval(7)">近7天</div>
      </div>
      <van-calendar 
        v-model:show="showCalendar" 
        type="range" 
        title="选择日期区间" 
        :min-date="new Date(new Date().getTime()- 60 * 24 * 3600 * 1000)" 
        :max-date="new Date()" 
        @confirm="onConfirm" 
      />
      <div id="secondChart" class="second-chart"></div>
    </div>
    <div class="source">
      <div class="name">广东省交通运输厅</div>
      <div class="name">数据来源：广东省航道事务中心</div>
    </div> 
    <!-- 弹窗 -->    
    <van-dialog 
      v-model:show="isShow" 
      confirm-button-text="我知道了" 
      confirm-button-color="#2D78ED"
    >
      <div class="dialog-title">{{ dialogTitle }}</div>
      <div class="dialog-content">{{ dialogContent }}</div>
    </van-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from "vue";

  // 引入api
  import {
    waterlevelDetail, //水位监测详情
    trendChart, //水位监测趋势
    getWaterlevelStationList, //获取水位监测站列表（可模糊搜索）
    getRegionList, //获取区域中心列表
    getWaterwayListNew, //获取所属航道
  } from "../../utils/apis";

  import * as echarts from 'echarts/core';
  import { GridComponent, TooltipComponent, DataZoomComponent } from 'echarts/components';
  import { LineChart } from 'echarts/charts';
  import { UniversalTransition } from 'echarts/features';
  import { CanvasRenderer } from 'echarts/renderers';
  import { showToast } from "vant";

  echarts.use([GridComponent, TooltipComponent, DataZoomComponent, LineChart, CanvasRenderer, UniversalTransition]);

  const clickSearch = () => {
    getWaterlevelStationListFn(searchValue.value,1);
  };
  const isChecked = ref(0);
  const handleChecked = (item,index) => {
    isChecked.value = index; 
    searchValue.value = item.waterlevelStation; 
    trendChartFn(); 
  };

  const searchValue2 = ref('吴川积美桥'); 
  const isShowSearchList2 = ref(false);
  const searchList2 = ref([]);
  const onSearch2 = () => {
    // trendChartFn();
    getWaterlevelStationListFn(searchValue2.value,2);
  };
  const handleChoose2 = (stationName) => {
    searchValue2.value = stationName;
    isShowSearchList2.value = false;
    trendChartFn();
  };

  const xAxisData = ref([]);
  const seriesData = ref([]);
  // 时段
  const date1 = ref('');
  const date2 = ref('');
  const timeInterval = ref(7);
  const showCalendar = ref(false);
  const getTimeInterval = (val) => {
    timeInterval.value = val;
    let time = new Date().getTime();
    if(val === 0){
      showCalendar.value = true;
    }else if(val === 1){
      let endTime = time - 1 * 24 * 3600 * 1000;
      date1.value = new Date(endTime).format('yyyy-MM-dd');
      date2.value = new Date(time).format('yyyy-MM-dd');
    }else if(val === 3){
      let endTime = time - 3 * 24 * 3600 * 1000;
      date1.value = new Date(endTime).format('yyyy-MM-dd');
      date2.value = new Date(time).format('yyyy-MM-dd');
    }else if(val === 7){
      let endTime = time - 7 * 24 * 3600 * 1000;
      date1.value = new Date(endTime).format('yyyy-MM-dd');
      date2.value = new Date(time).format('yyyy-MM-dd');
    }
    trendChartFn();
  };
  const onConfirm = (values) => {
    const [start, end] = values;
    date1.value = start.format('yyyy-MM-dd');
    date2.value = end.format('yyyy-MM-dd');
    showCalendar.value = false;
    trendChartFn();
  };
  const trendChartFn = () => {
    trendChart(searchValue.value,date1.value,date2.value).then((res) => {
      if(res.code === 200){
        xAxisData.value = [];
        seriesData.value = [];
        res.data.forEach((item) => {
          if(timeInterval.value === 1){
            xAxisData.value.push(item.reporttime.slice(11,16));
          }else{
            xAxisData.value.push(item.reporttime.slice(5,10));
          }           
          seriesData.value.push(item.waterlevelValue);
        });
        initSecondChart();
      }
    });
  };
  const initSecondChart = () => {
    let secondChart = echarts.getInstanceByDom(document.getElementById("secondChart"));
    if(secondChart != null && secondChart != "" && secondChart != undefined){
      secondChart.dispose();
    }
    secondChart = echarts.init(document.getElementById('secondChart'));
 
    let option;
    option = {
      tooltip: {
        trigger: 'axis',
        confine: true, //限制在图表区域内
      },
      grid: {
        top: '20%',
        left: '10%',
        right: '60',
        bottom: '5%',
        containLabel: true
      },
      dataZoom: [
        {
          show: false,
          type: "inside",
          maxValueSpan: 60,
          zoomLock: false,
        },
      ],
      xAxis: {
        type: 'category',
        name: '时间',
        data: xAxisData.value,
        axisTick: {
          alignWithLabel: true, //控制刻度线是否与刻度标签对齐
          show: false, //是否显示刻度线
        },
        nameTextStyle: {
          fontWeight: "500",
          fontSize: "10px",
          color: "rgba(0,0,0,0.45)",
        },
        axisLabel: { 
          interval: 'auto', 
          rotate: 60,
          // overflow: 'truncate',
          // formatter(v){
          //     return ' '.repeat(4)+v+' '.repeat(4);
          // }
        },
      },
      yAxis: {
        type: 'value',
        name: '水位值（m）',
        nameTextStyle: {
          fontWeight: "500",
          fontSize: "10px",
          color: "rgba(0,0,0,0.45)",
        },
        nameGap: 15,  
      },
      series: [
        {
          data: seriesData.value,
          type: 'line',
          itemStyle: {
            color: '#75a7d4'
          },
        }
      ]
    };
    option && secondChart.setOption(option);

  };

  const searchValue = ref(''); 
  const isShowSearchList = ref(false);
  const searchList = ref([]);
  const onSearch = () => {    
    getWaterlevelStationListFn(searchValue.value,1);
  };

  const getWaterlevelStationListFn = (val,type) => {
    getWaterlevelStationList(val).then((res) => {
      if(res.code === 200 && res.data.length){
        if(type === 1){
          isShowSearchList.value = true;
          searchList.value = res.data;
        }else if(type === 2){
          isShowSearchList2.value = true;
          searchList2.value = res.data;
        }        
      }else{
        showToast("暂无数据");
      }
    });
  };
  const handleChoose = (stationName) => {
    searchValue.value = stationName;
    leftVal.value = "";
    rightVal.value = "";
    isShowSearchList.value = false;
    waterlevelDetailFn();
  };

  // 下拉选择
  const showLeft = ref(false);
  const leftVal = ref("");
  const leftList = ref([]);
  const showRight = ref(false);
  const rightVal = ref("");
  const rightList = ref([]);
  const setLeft = (item) => {
    if(item.region === "全部"){
      leftVal.value = "";
      showLeft.value = false;
      rightVal.value = "";
      searchValue.value = "";
      waterlevelDetailFn();
    }else{
      leftVal.value = item.region;
      showLeft.value = false;
      rightVal.value = "";
      searchValue.value = "";
      getWaterwayListFn(item.region);
      waterlevelDetailFn();
    }
  };
  const getLeftList = () => {
    showLeft.value = !showLeft.value;
    showRight.value = false;
  };
  const setRight = (item) => {
    rightVal.value = item.waterwayName;
    showRight.value = false;
    searchValue.value = "";
    waterlevelDetailFn();
  };
  const getRightList = () => {
    showRight.value = !showRight.value;
    showLeft.value = false;
  };

  const waterlevelStationSum = ref('');
  const tableData1 = ref([]);
  const waterlevelDetailFn = () => {
    waterlevelDetail(leftVal.value,rightVal.value,searchValue.value).then((res) => {
      if(res.code === 200 && res.data.length){
        waterlevelStationSum.value = res.data[0].waterlevelStationSum;
        tableData1.value = res.data[0].waterwayDetail;
        searchValue.value = res.data[0].waterwayDetail[0].waterlevelStation;
        trendChartFn();
      }
    });
  };

  // 弹窗
  const isShow = ref(false);
  const dialogTitle = ref("");
  const dialogContent = ref("");
  const handleShow = () => {    
    let secondChart = echarts.getInstanceByDom(document.getElementById("secondChart"));
    secondChart.dispatchAction({
      type: 'hideTip'
    });
    dialogTitle.value = "水位遥测遥报监测终端总数量";
    dialogContent.value = "水位遥测遥报终端的总数（接入智慧航道系统的航道部门维护和非航道部门维护的桥梁）（注：明细【属性信息项】：区域中心、所属航道、监测站名称、水位值、数据更新时间）";
    isShow.value = true;
  };

  //获取日期
  const currentYearMonth1 = ref("");
  const currentYearMonth2 = ref("");

  //获取区域中心
  const getRegionListFn = () => {
    getRegionList().then((res) => {
      if(res.code === 200 && res.data.length){        
        let item = { region: "全部" };
        leftList.value = res.data;
        leftList.value.unshift(item)
      }
    });
  };

  //获取所属航道
  const getWaterwayListFn = (region) => {
    getWaterwayListNew(region).then((res) => {
      if(res.code === 200 && res.data.length){
        rightList.value = res.data;
      }
    });
  };

  onMounted(() => {
    if(sessionStorage.getItem("watermarkTxt")){
      //加水印
      watermark.init({ 
        watermark_x: -30, // 水印起始位置x轴坐标
        watermark_y: -20, // 水印起始位置Y轴坐标
        watermark_x_space: 20, // 水印x轴间隔
        watermark_y_space: 80, // 水印y轴间隔
        watermark_alpha: 0.07, // 水印透明度
        watermark_fontsize: '14px', // 水印字体大小
        watermark_width: 100, // 水印宽度
        watermark_height: 30,
        watermark_txt: sessionStorage.getItem("watermarkTxt"), // 水印的内容
        watermark_angle: 25, // 水印倾斜度数
        watermark_rows: 0, // 水印行数
        watermark_cols: 0, // 水印列数
        watermark_font: '微软雅黑', // 水印字体
        watermark_color: 'black', // 水印字体颜色 
      });
    }
    
    currentYearMonth1.value = new Date().getFullYear() + ".01";
    currentYearMonth2.value = new Date().format("yyyy.MM");
    date1.value = new Date(new Date().getTime()- 7 * 24 * 3600 * 1000).format('yyyy-MM-dd');
    date2.value = new Date().format('yyyy-MM-dd');
    
    waterlevelDetailFn();
    // trendChartFn();
    getRegionListFn();
  });

</script>

<style lang="scss" scoped>
  .container{
    width: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    .header{
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.08);
      .title {
        color: #262626;
        font-size: 18px;
        font-weight: 500;
        padding: 12px 0px 10px 20px;
        position: relative;
      }
      .time {
        display: flex;
        align-items: center;
        color: #8C8C8C;        
        font-size: 14px;
        padding-right: 20px;
        img{
          width: 18px;
          height: 18px;
          padding-right: 5px;
        }
      }
    }
    .unit {
      display: flex;
      flex-direction: row-reverse;
      padding: 8px 20px 8px 0;
      font-size: 12px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.45);
    }
    .content{
      background-color: #fff;
      border-radius: 8px;
      margin: 0px 20px 20px 20px;
      .title{
        color: #262626;
        font-size: 16px;
        font-weight: 500;
        position: relative;       
        padding: 16px 0;
        margin: 0 16px;
        border-bottom: 1px solid #D9D9D9;
        display: flex;
        justify-content: space-between;
        align-items: center;
        img{
          width: 16px;
          height: 16px;
        }
      }
      .amount{
        display: flex;        
        .info{
          width: 100%;
          height: 80px;
          background-image: url(../../static/images/water-level-bg.png);
          background-repeat: no-repeat;
          background-size: 100% 80px;
          display: flex;
          align-items: center;
          margin: 16px;
          img{
            width: 42px;
            height: 42px;
            margin: 0 16px;
          }
          .detail{
            display: flex;
            flex-direction: column;
            .name{
              font-size: 14px;
              color: #595959;
            }
            .value{
              font-size: 24px;
              font-weight: 800;
              color: #0473DE;
            }
          }
        }
      }
      .subtitle{
        display: flex;
        justify-content: center;
        align-items: center;
        color: #737579;
        font-size: 14px;
        font-weight: bold;     
        .value{
          background-color: #e3e9fb;
          padding: 4px 16px;
          border-radius: 10px;
        }
      }
      .second-chart{
        height: 200px;
        margin: 10px 0;
      }
      // :deep(.van-search__content) {
      //   background: #fff;
      //   border: 1px solid #d4d4d4;
      //   border-radius: 20px;
      // }    
      // :deep(.van-dropdown-menu__bar) {
      //   height: 30px;        
      // } 
      .table {
        margin: 16px;
        overflow: hidden;
        padding-bottom: 10px;
        th {
          padding: 4px;
          // border: 1px solid #d9d9d9;
          font-size: 14px;
          font-weight: 500;
          color: rgba(0, 0, 0, 0.85);
          background-color: #f8f9fb;
        }
        .tbody {
          height: 80px; /* 设置表格体容器的高度 */
          overflow-y: auto; /* 启用垂直滚动条 */
          width: calc(110% - 24px);
        }
        .tbody {
          td {
            padding: 4px;
            // border: 1px solid #d9d9d9;
            font-size: 14px;
            font-weight: 400;
            color: #595959;
            text-align: center;
          }
        }
      }
      .choose {
        display: flex;
        // justify-content: flex-end;
        margin-left: 16px;
        .left,
        .right {
          width: 124px;
          height: 22px;
          background: #ffffff;
          border-radius: 0px 0px 0px 0px;
          opacity: 1;
          // border: 1px solid #d9d9d9;
          text-align: center;
          line-height: 22px;
          position: relative;
          .option {
            .choose-input {
              width: 94%;
              height: 92%;
              // border: none;
              text-align: center;
            }
            .choose-list {
              position: absolute;
              font-size: 12px;
              font-weight: 400;
              color: #595959;
              width: 124px;
              background: #fff;
              // left: -2px;
              // top: 25px;
              z-index: 999;
              .list {
                max-height: 180px;
                overflow-y: scroll;
                margin-top: -2px;
                border: 1px solid #ccc;
                li {
                  list-style-type: none;
                }
              }
            }
          }
        }
        .right {
          margin-right: 25px;
          margin-left: 16px;
        }
      }
      .tab-list{
        display: flex;
        margin: 16px 16px 0px 16px;
        .tab-item{
          background: #FFFFFF;
          box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.08);
          border-radius: 4px;
          opacity: 1;
          border: 1px solid #F0F0F0;
          padding: 4px 8px;
          margin-right: 10px;
        }
        .active{
          background: #165DFF;
          color: #fff;
        }
      }
      .table-box {
        width: 320px;
        min-height: 100px;
        // max-height: 200px;
        overflow: scroll;
        scrollbar-width: none;
        scrollbar-color: transparent;
        -ms-overflow-style: none;
        .table {
          // margin-left: 18px;
          // margin-right: 16px;
          width: 320px;
          min-height: 100px;
          max-height: 200px;
          overflow: scroll;
          scrollbar-width: none;
          scrollbar-color: transparent;
          -ms-overflow-style: none;
          th,
          td {
            padding: 4px;
            color: #595959;
            text-align: center;
          }
          .tbody {
            height: 100px; /* 设置表格体容器的高度 */
            overflow-y: auto; /* 启用垂直滚动条 */
            width: 100%;
            overflow-x: auto;
          }
          tr:nth-child(even) {
            background-color: #f3f7ff;
          }
        }
      }
      .table-box::-webkit-scrollbar {
        width: 0;
        height: 0;
        background-color: transparent;
      }
      .table-box::-webkit-scrollbar-thumb {
        background-color: transparent;
      }
      .search{
        position: relative; 
        .search-list{
          height: 180px;
          overflow-y: scroll;
          border: 1px solid #f7f8fa;
          margin: -10px 12px 0px 12px;
          position: absolute;
          background-color: #fff;
          width: 100%;
          width: -moz-available;
          width: -webkit-fill-available;
          width: fill-available;
          z-index: 9999;
          .search-item{
            margin: 10px 20px;
            padding-bottom: 10px;
            color: #595959;
            border-bottom: 1px solid #ccc;
          }
        }
      }
      .sub-name{
        font-size: 14px;
        margin: 16px 16px 0px 16px;
      }
    }
    .source{
      text-align: center;
      padding: 5px 0;
      color: #8C8C8C;
      .name{
        margin-bottom: 5px;
      }
    }
    .dialog-title{
      text-align: center;
      padding: 20px 0;
      font-size: 16px;
      font-weight: 500;
      color: #000000;
    }
    .dialog-content{
      text-align: center;
      padding: 0 20px 20px 20px;
      font-size: 14px;
      font-weight: 400;
    }
    :deep(.van-dialog__content){
      min-height: 118px;
      max-height: 293px;
      overflow-y: scroll;
    }
  }
</style>